use actix_web::{HttpRequest, delete, get, post, put, web};

use log::{info, trace};
use rbase::{
    define::{ApiError, ApiResponse},
    id_utils::{id2str, str2id},
};
use serde::{Deserialize, Serialize};

use crate::{
    db::entities::role::Model,
    rest_api::service::{auth_check::get_user_from_request, srv_role},
};
use anyhow::Result;

#[derive(Clone, Debug, Deserialize)]
pub struct CreateParams {
    pub name: String,
    pub role: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UpdateParams {
    pub name: String,
    pub role: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Role {
    pub id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<i64>,
}

impl Role {
    pub fn from_model(entity: &Model) -> Self {
        Role {
            id: id2str(entity.id),
            name: entity.name.clone(),
            role: entity.role.clone(),
            created_at: entity.created_at,
            modified_at: entity.modified_at,
        }
    }

    pub fn to_model(&self) -> Result<Model> {
        Ok(Model {
            id: str2id(&self.id)?,
            name: self.name.clone(),
            role: self.role.clone(),
            created_at: self.created_at,
            modified_at: self.modified_at,
            ..Default::default()
        })
    }
}

#[derive(Deserialize, Debug)]
pub struct SearchParams {
    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub offset: Option<u64>,

    #[serde(default)]
    pub limit: Option<u64>,

    #[serde(default)]
    pub order_by: Option<String>,

    #[serde(default)]
    pub order: Option<String>,
}

#[get("/api/v1/roles")]
async fn list_roles(req: HttpRequest, query_params: web::Query<SearchParams>) -> Result<ApiResponse, ApiError> {
    let role_search_params = query_params.into_inner();
    trace!("list_roles query: {:?}", role_search_params);
    let user = get_user_from_request(&req)?;
    let (roles, total) = srv_role::search(&user, &role_search_params).await?;
    Ok(ApiResponse::datas(roles, total))
}

#[post("/api/v1/roles")]
async fn create_role(req: HttpRequest, req_body: String) -> Result<ApiResponse, ApiError> {
    trace!("create_role body: {}", req_body);
    let user = get_user_from_request(&req)?;
    let new_role: CreateParams = serde_json::from_str(&req_body)?;
    let role = srv_role::create_role(&user, &new_role).await?;
    Ok(ApiResponse::data(role))
}

#[get("/api/v1/roles/{id}")]
async fn get_role(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    let role_id = path_params.into_inner();
    trace!("get_role path: {:?}", role_id);
    let _user = get_user_from_request(&req)?;
    let role = srv_role::find_role_by_id(&role_id).await?;
    Ok(ApiResponse::data(role))
}

#[delete("/api/v1/roles/{id}")]
async fn delete_role(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("delete_role path: {:?}", path_params);
    let user = get_user_from_request(&req)?;
    let role_id = path_params.into_inner();
    srv_role::delete_role_by_id(&user, &role_id).await?;
    Ok(ApiResponse::success())
}

#[put("/api/v1/roles/{id}")]
async fn update_role(req: HttpRequest, req_body: String, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("update_role path: {:?}, body: {}", path_params, req_body);
    let user = get_user_from_request(&req)?;
    let new_role: UpdateParams = serde_json::from_str(&req_body)?;
    let role_id = path_params.into_inner();
    srv_role::update_role_by_id(&user, &role_id, &new_role).await?;
    Ok(ApiResponse::success())
}

pub fn config(cfg: &mut web::ServiceConfig) {
    info!("Configuring role APIs");
    cfg.service(list_roles);
    cfg.service(create_role);
    cfg.service(get_role);
    cfg.service(delete_role);
    cfg.service(update_role);
}
